package com.study.lu.thread.readwritelock;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <b>System：</b>incommonusefactory<br/>
 * <b>Title：</b>ReadWriteLockTest.java<br/>
 * <b>Description：</b> 对功能点的描述<br/>
 * <b>@author： </b>raoluping<br/>
 * <b>@date：</b>2017/12/23 17:31<br/>
 * <b>@version：</b> 1.0.0.0 <br/>
 * <b>Copyright (c) 2017 ASPire Tech.</b>
 */
public class ReadWriteLockTest {
    private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private static int value = 0;

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(new WriteThread()).start();
        }

        for (int i = 0; i < 100; i++) {
            new Thread(new ReadThread()).start();
        }
    }

    static class ReadThread implements Runnable {

        @Override
        public void run() {
            readWriteLock.readLock().lock();
            try {
                System.out.println("读线程 在读 value:" + value);
            } finally {
                readWriteLock.readLock().unlock();
            }
        }
    }

    static class WriteThread implements Runnable {

        @Override
        public void run() {
            readWriteLock.writeLock().lock();
            Random random = new Random();
            try {
                value = value + random.nextInt(10);
                Thread.sleep(1000);
                System.out.println("写线程 执行写操作后  value=" + value);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {

                readWriteLock.writeLock().unlock();
            }
        }
    }

}
